<template>
  <div>
    <el-upload
      action="/api/v1/upload/picture"
      :on-exceed="handleExceed"
      :data="uploadParams"
      ref="upload"
      drag
      multiple
      :list-type="'picture-card'"
      :http-request="handleUpload"
      :before-upload="beforeUpload"
      :file-list="fileList"
    >
      <svg
        viewBox="0 0 24 24"
        fill="none"
        xmlns="http://www.w3.org/2000/svg"
        width="20px"
        height="20px"
        style="margin:0 auto;color:#82827e"
        focusable="false"
        aria-hidden="true"
      >
        <path
          fill-rule="evenodd"
          clip-rule="evenodd"
          d="M17.8395 8.05827C17.1837 5.16226 14.5944 3 11.5 3C7.91015 3 5 5.91015 5 9.5C5 10.0204 5.06115 10.5264 5.17665 11.0114C2.84229 11.1772 1 13.1234 1 15.5C1 17.9853 3.01469 20 5.49995 20H17C20.3137 20 23 17.3137 23 14C23 10.9712 20.7558 8.46659 17.8395 8.05827ZM12.3201 8.26674C12.1347 8.11222 11.8653 8.11222 11.6799 8.26674L6.53047 12.5579C6.35084 12.7076 6.45669 13 6.69051 13H10V17.5C10 17.7761 10.2239 18 10.5 18H13.5C13.7761 18 14 17.7761 14 17.5V13H17.3095C17.5433 13 17.6492 12.7076 17.4695 12.5579L12.3201 8.26674Z"
          fill="currentColor"
        ></path>
      </svg>
      <div slot="file" slot-scope="{ file }">
        <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
        <span class="el-upload-list__item-actions">
          <span class="el-upload-list__item-preview" @click="handleBack(file)">
            <i class="el-icon-back"></i>
          </span>
          <span
            v-if="!disabled"
            class="el-upload-list__item-delete"
            @click="handleRemove(file)"
          >
            <i class="el-icon-delete"></i>
          </span>
          <span
            v-if="!disabled"
            class="el-upload-list__item-delete"
            @click="handleNext(file)"
          >
            <i class="el-icon-right"></i>
          </span>
        </span>
      </div>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="imgUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import { calculateSHA512 } from '@/utils/encrypt'
import {
  uploadFileToCos,
  uploadMusicScoreToCos,
  deleteMultipleUploadFile,
  deleteUploadFile
} from '@/api/cos'
import md5 from 'md5'

import { getAccessToken } from '@/utils/auth'
export default {
  props: {
    referenced_urls: {
      type: Array,
      required: false
    }
  },
  watch: {
    referenced_urls: {
      immediate: true,
      handler(val) {
        // 如果传递了url
        if (val) {
          // 清空fileList
          this.fileList = []
          this.imgList = val
          this.fileList = val.map(item => {
            return {
              name: `edited-image${item}`,
              url: item
            }
          })
        }
      }
    }
  },
  data() {
    return {
      fileList: [],
      imgUrl: '',
      uploadParams: {
        img: null
      },
      dialogVisible: false,
      disabled: false,
      currentFile: null,
      imgList: [],
      prefix: ''
    }
  },
  computed: {},
  mounted() {
    this.$nextTick(() => {
      // 监视发布事件
      this.$bus.$on('handleConfirm', this.SetImgList)
      // 获取前缀
      this.prefix = md5(
        Date.now().toString() +
          '/' +
          Math.floor(Math.random() * 10000).toString()
      )
    })
  },
  methods: {
    handleBack(file) {
      let fileIndex = this.fileList.findIndex(f => f === file)
      if (fileIndex === -1) {
        return
      }
      if (fileIndex === 0) {
        // 如果是首位元素，则将其移到末尾
        this.fileList.splice(fileIndex, 1) // 先将元素从当前位置删除
        this.fileList.push(file) // 再将元素添加到末尾

        // 将 referenced_urls 也移位
        let referencedUrl = this.referenced_urls.splice(fileIndex, 1)
        this.referenced_urls.push(referencedUrl[0])

        return
      }
      // 将当前文件与前一个文件交换位置
      this.fileList.splice(fileIndex, 1) // 先将元素从当前位置删除
      this.fileList.splice(fileIndex - 1, 0, file) // 再将元素添加到前一个位置

      // 将 referenced_urls 也移位
      let referencedUrl = this.referenced_urls.splice(fileIndex, 1)
      this.referenced_urls.splice(fileIndex - 1, 0, referencedUrl[0])
    },

    handleNext(file) {
      let fileIndex = this.fileList.findIndex(f => f === file)
      if (fileIndex === -1) {
        return
      }
      if (fileIndex === this.fileList.length - 1) {
        // 如果是末尾元素，则将其移到首位
        this.fileList.splice(fileIndex, 1) // 先将元素从当前位置删除
        this.fileList.unshift(file) // 再将元素添加到首位

        // 将 referenced_urls 也移位
        let referencedUrl = this.referenced_urls.splice(fileIndex, 1)
        this.referenced_urls.unshift(referencedUrl[0])

        return
      }
      // 将当前文件与后一个文件交换位置
      this.fileList.splice(fileIndex, 1) // 先将元素从当前位置删除
      this.fileList.splice(fileIndex + 1, 0, file) // 再将元素添加到后一个位置

      // 将 referenced_urls 也移位
      let referencedUrl = this.referenced_urls.splice(fileIndex, 1)
      this.referenced_urls.splice(fileIndex + 1, 0, referencedUrl[0])
    },
    // 设置图片列表至vuex仓库
    SetImgList() {
      console.log('handleConfirm', this.imgList)
      // 存储数据到vuex
      this.$store.commit('musicScore/SETMUSICSCORELIST', this.imgList)
      this.$store.commit('musicScore/SETFILEHASH', this.prefix)
    },
    handleExceed(files, fileList) {
      console.log('超出限制')
      // 文件数量超过限制的回调函数
      this.$message.warning(`只能上传 ${this.limit} 个文件`)
    },
    // 删除图片
    async handleRemove(file) {
      console.log(file)
      // cos清空数据
      const index = this.fileList.indexOf(file)
      console.log(index, this.imgList[index])

      if (index !== -1) {
        // 整理数据
        const formData = new FormData()
        formData.append('url', this.imgList[index])
        // 检测是否可以删除
        const res = await this.$API.upload.DetectCosRemove(formData)
        if (res.status == 200) {
          // 删除多余图片
          const response = await deleteUploadFile(file.name)
          if (response.statusCode == 200 || response.statusCode == 204) {
            this.fileList.splice(index, 1)
            this.imgList.splice(index, 1)
          }
        }
        // 如果其他资源引用了
        else if (res.status == 422) {
          this.fileList.splice(index, 1)

          this.imgList.splice(index, 1)
        }
      }
      // 本地清空数据
      // const index = this.fileList.indexOf(file);
      // console.log(index, this.imgList[index])

      // if (index !== -1) {
      //   // 整理数据
      //   const formData = new FormData()
      //   formData.append('url', this.imgList[index])
      //   // 删除多余图片
      //   const res = await this.$API.upload.DeleteAlreadyUploadFile(formData)
      //   if (res.status == 200 || res.status == 422) {
      //     this.fileList.splice(index, 1);

      //     this.imgList.splice(index, 1);

      //   }
      // }
    },

    // 放大缩略图
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleDownload(file) {
      console.log(file)
    },
    async handleUpload({ file }) {
      console.log('file', file)
      // 格式校验
      const allowedExtensions = ['.jpg', '.jpeg', '.png', '.gif']
      const allowedMimeTypes = ['image/jpeg', 'image/png', 'image/gif']

      const fileExtension = file.name
        .substring(file.name.lastIndexOf('.'))
        .toLowerCase()
      const fileMimeType = file.type
      // 检查文件扩展名
      if (!allowedExtensions.includes(fileExtension)) {
        this.$message.error('只能上传 JPG、JPEG、PNG 或 GIF 格式的图片')
        this.fileList = []
        return
      }

      // 检查文件 MIME 类型
      if (!allowedMimeTypes.includes(fileMimeType)) {
        this.$message.error('只能上传 JPG、JPEG、PNG 或 GIF 格式的图片')
        this.fileList = []
        return
      }
      // 本地存储
      // cos对象存储
      try {
        const response = await uploadMusicScoreToCos(
          file,
          file.name,
          this.prefix
        )
        console.log(response)
        let img_url = 'http://' + response.Location
        // 上传成功后将文件添加到 fileList 中
        this.fileList.push({
          name: file.name,
          url: img_url
        })
        this.imgList.push(img_url)
        // 清空当前文件
        this.currentFile = null
      } catch (error) {
        console.error(error)
        this.$message.error('上传失败')
      }
      // 以8192字节的形式读取文件
      // const chunkSize = 8192;
      // let currentByte = 0;
      // // 文件读取
      // fileReader.onload = async () => {
      //   const arrayBuffer = fileReader.result;
      //   const uint8Array = new Uint8Array(arrayBuffer);
      //   // 格式转换
      //   const fileBlob = new Blob([arrayBuffer], { type: this.currentFile.type });
      //   // 生成hash值
      //   const file_hash = await calculateSHA512(fileBlob);
      //   const datas = this.$qs.stringify({ file_hash })
      //   console.log(file_hash, datas)
      //   try {
      //     // 验证文件是否存在
      //     const res = await this.$API.upload.CheckExist(datas)
      //     console.log(res)
      //     // 发起监听窗口关闭事件
      //     this.$bus.$on("RemoveAlreadyUploadImage", this.RemoveAlreadyUploadImage)
      //     // 如果存在秒传地址
      //     if (res && res.status == 200) {
      //       console.log('success', res.data.url)
      //       this.imgList.push(res.data.url)
      //       return;
      //     }
      //     // 整理数据
      //     const formData = new FormData()
      //     formData.append('img', this.currentFile)
      //     // 上传图片
      //     const response = await this.$API.upload.uploadImage(formData)
      //     console.log(response)
      //     if (response.status == 200) {
      //       // this.fileList.push(this.currentFile)
      //       this.imgList.push(response.data.url)

      //       // 数据传递
      //       // this.$store.commit("upload/SETIMGURL", res.data.url)

      //     }
      //   } catch (error) {
      //     this.$message.error("文件检查请求失败")
      //     return;
      //   }
      // }
      // fileReader.readAsArrayBuffer(this.currentFile);
    },
    beforeUpload(file) {
      // 封装文件
      const fileObject = {
        name: file.name,
        url: URL.createObjectURL(file)
      }
      // 将文件加入fileList
      this.fileList.push(fileObject)
      this.currentFile = file

      // Prevent automatic upload
      // return false;
    },

    // 移除多余的图片
    async RemoveAlreadyUploadImage() {
      if (!this.imgList) return
      const formData = new FormData()
      formData.append('urls', this.imgList)
      const res = await this.$API.upload.BatchDeleteAlreadyUploadFile(formData)
      if (res.status == 200 || res.status == 422) {
        // 初始化数据
        this.imgList = []
        this.fileList = []
      }
    }
  }
}
</script>
